package com.smartmedi.ai.utils;

import com.smartmedi.ai.config.FtpConfig;
import jakarta.annotation.Resource;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;

@Component
public class FtpUtil {

    @Resource
    private FtpConfig ftpConfig;

    /**
     * 从FTP下载文件，返回输入流
     */
    public InputStream downloadFile(String ftpFilePath) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            // 1. 连接FTP服务器
            ftpClient.connect(ftpConfig.getHost(), ftpConfig.getPort());
            boolean loginSuccess = ftpClient.login(ftpConfig.getUsername(), ftpConfig.getPassword());
            if (!loginSuccess) {
                throw new IOException("FTP登录失败，用户名或密码错误");
            }

            // 2. 检查连接状态
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                throw new IOException("FTP连接失败，响应码：" + replyCode);
            }

            // 3. 设置传输模式
            ftpClient.setControlEncoding(ftpConfig.getEncoding());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制传输，支持所有文件类型

            // 4. 下载文件
            InputStream inputStream = ftpClient.retrieveFileStream(ftpFilePath);
            if (inputStream == null) {
                throw new IOException("FTP文件不存在：" + ftpFilePath);
            }
            return inputStream;
        } catch (IOException e) {
            throw new IOException("FTP下载失败：" + e.getMessage());
        }
    }
}